<?php
namespace Common\Model;

use Think\Model;

/**
 * Created by PhpStorm.
 * User: ywk
 * Date: 2018/10/24
 * Time: 13:50
 * 代理商订单分润统计以及相关统计
 */
class OrderModel extends Model
{
    /**
     *
     */
    protected $order_id = '';
    protected $order_amount = array();  // 实例
    protected $user_rate = array();
    protected $operator_id = '';

    public function getAgentCommissionByOrderId($order_Id)
    {
        if (empty($order_Id)) {
            echo '订单号错误';
            return [];
        }

        if (empty($this->order_id)) {
            $this->order_id = $order_Id;
        }

        $map = array();
        $map['o.state'] = 1;
        $map['o.orderid'] = $this->order_id;

        $info = M('order')
            ->alias('o')
            ->field("o.*,u.agent_id")
            ->join('__USER__ u ON o.uid = u.id', 'LEFT')
            ->where($map)
            ->find();

        if (empty($info) || empty($info['agent_id'])) {
            echo "该订单的用户目前还没有代理商";
            return [];
        }
        if (empty($this->order_amount)) {
            $data = [];
            $data['instance'] = $info['ruleprice']; // 实例的价格
            $data['system_disk'] = $info['xiprice']; // 系统盘的价格
            $data['storage_disc'] = $info['shuprice']; // 存储盘的价格
            $data['network'] = $info['widthprice']; // 公网带宽的价格
            $data['total'] = $info['money']; // 公网带宽的价格
            $this->order_amount = $data;//订单金额
            // 测试数据：目前是只做阿里云一家的，后期可能会做其他的运营商
            $this->operator_id = 1;// 运营商id ： 设置为 “阿里云”
        }
        if (empty($this->user_rate)) {
            //用户折扣率（这里没有多大价值，应该是计算商品价格的时候，订单价格 = 商品价格*折扣率）如果会员没有挂代理商则这里直接置为1
            $data = [];
            $data['instance'] = $info['rulepid'] ? $info['rulepid'] : 1; // 实例的折扣率
            $data['system_disk'] = $info['xipid'] ? $info['xipid'] : 1; // 系统盘的折扣率
            $data['storage_disc'] = $info['shupid'] ? $info['shupid'] : 1; // 存储盘的折扣率
            $data['network'] = $info['widthpid'] ? $info['widthpid'] : 1; // 公网带宽的折扣率
            $this->user_rate = $data;//折扣率
        }

        $where['admin_id'] = $info['agent_id'];
        $where['status'] = 1;

        //获取代理商信息
        $agent_info = $this->getParentAgentInfo($info['agent_id']);

        $this->calculateAgentOrder($agent_info);

        //记录代理商的每笔新增收入
        $this->saveSettleMent();
    }

    /**
     * 记录代理商的每笔新增收入
     */
    public function saveSettleMent()
    {
        $data = array();
        $con = array();
        $con['order_id'] = $this->order_id;
        $db_data = M('agent_commission_order_record')->where($con)->field("agent_id, agent_name, sum(order_profit) as increase")->group('agent_id')->select();
        if (empty($db_data)) {
            $data['state'] = false;
            $data['msg'] = '收入为空！';
            return $data;
        }
        foreach ($db_data as $index => $db_datum) {
            // 保存收入明细表
            $insert = array();
            $insert['agent_id'] = $db_datum['agent_id'];
            $insert['agent_name'] = $db_datum['agent_name'];
            $insert['order_id'] = $this->order_id;
            $insert['increase'] = $db_datum['increase'];
            $result = M('settlement')->add($insert);
            //更新 代理商账户 可提现金额
            M('agent')->where('admin_id=' . $db_datum['agent_id'])->setInc('withdrawn', $db_datum['increase']);
        }
    }

    //计算代理商订单分润记录
    public function calculateAgentOrder($agent_info, $child_agent_info = [], $depth = 0)
    {
        $self_rate = $agent_info['rate'];
        if (isset($depth) && $depth == 0) {
            // 无下级代理商，则直接计算收入（上级代理商发放的）即可
            $parent_name = $this->getParentAgentName($agent_info['shangji']);
            $this->save_Commission_Order_Log($self_rate, 0, $agent_info, 'income', $parent_name);
        } else {
            // 有下级代理商，需要计算收入（上级代理商发放的） 和支出（分给下级代理商的金额）
            $child_rate = $child_agent_info['rate'];
            $child_name = $child_agent_info['admin_name'];
            $parent_name = $this->getParentAgentName($agent_info['shangji']);
            $this->save_Commission_Order_Log($self_rate, $child_rate, $agent_info, 'income', $parent_name);
            $this->save_Commission_Order_Log($self_rate, $child_rate, $agent_info, 'spend', $child_name);
        }

        //依次往上级递归调用，计算上级代理的账务明细
        $parent_agent_id = $agent_info['shangji'];
        $parent_agent_info = $this->getParentAgentInfo($parent_agent_id);
        // 不存在上级，则跳出递归
        if (empty($parent_agent_info) || empty($parent_agent_info['admin_id'])) {
            return;
        }
        $depth++;
        $this->calculateAgentOrder($parent_agent_info, $agent_info, $depth);
    }

    /**
     * @return string
     */
    public function save_Commission_Order_Log($self_rate, $child_rate = 0, $agent_info, $type = 'income', $name)
    {
        //收入
        if ($type == "income") {
            //计算实例并保留两位小数
            $instance = $this->order_amount['instance'] * ($this->user_rate['instance'] - $self_rate['instance']);
            $instance = sprintf("%.2f", $instance);

            //计算系统盘并保留两位小数
            $system_disk = $this->order_amount['system_disk'] * ($this->user_rate['system_disk'] - $self_rate['system_disk']);
            $system_disk = sprintf("%.2f", $system_disk);

            //计算数据盘并保留两位小数
            $storage_disc = $this->order_amount['storage_disc'] * ($this->user_rate['storage_disc'] - $self_rate['storage_disc']);
            $storage_disc = sprintf("%.2f", $storage_disc);

            //计算公网带宽并保留两位小数
            $network = $this->order_amount['network'] * ($this->user_rate['network'] - $self_rate['network']);
            $network = sprintf("%.2f", $network);

            //计算流水总额并保留两位小数
            $money = $instance + $system_disk + $storage_disc + $network;
            $money = sprintf("%.2f", $money);
            $depict = sprintf("收入：收到上级【%s】打款 %2d 元", $name, $money);
        }
        //支出
        if ($type == "spend") {
            //计算实例并保留两位小数
            $instance = $this->order_amount['instance'] * ($this->user_rate['instance'] - $child_rate['instance']);
            $instance = sprintf("%.2f", $instance);
            $instance *= -1;

            //计算系统盘并保留两位小数
            $system_disk = $this->order_amount['system_disk'] * ($this->user_rate['system_disk'] - $child_rate['system_disk']);
            $system_disk = sprintf("%.2f", $system_disk);
            $system_disk *= -1;

            //计算数据盘并保留两位小数
            $storage_disc = $this->order_amount['storage_disc'] * ($this->user_rate['storage_disc'] - $child_rate['storage_disc']);
            $storage_disc = sprintf("%.2f", $storage_disc);
            $storage_disc *= -1;

            //计算公网带宽并保留两位小数
            $network = $this->order_amount['network'] * ($this->user_rate['network'] - $child_rate['network']);
            $network = sprintf("%.2f", $network * (-1));
            $network *= -1;

            //计算流水总额并保留两位小数
            $money = $instance + $system_disk + $storage_disc + $network;
            $money = sprintf("%.2f", $money);
            $depict = sprintf("支出：发放给下级【%s】 %2d 元", $name, $money);
            $money *= -1;
        }

        $commission_order_info = [];
        $commission_order_info['order_id'] = $this->order_id;
        $commission_order_info['agent_id'] = $agent_info['admin_id'];
        $commission_order_info['agent_name'] = $agent_info['admin_name'];
        $commission_order_info['create_time'] = date("Y-m-d H:i:s", time());
        $commission_order_info['instance'] = $instance; //实例
        $commission_order_info['system_disk'] = $system_disk; //系统盘
        $commission_order_info['storage_disc'] = $storage_disc; //存储盘
        $commission_order_info['network'] = $network; //公网带宽
        $commission_order_info['order_profit'] = $money; //总额
        $commission_order_info['depict'] = $depict;

        //保存订单分润记录
        $this->addAgentCommissionOrder($commission_order_info);
    }


    public function getParentAgentName($parent_agent_id)
    {
        $name = '平台';
        if (empty($parent_agent_id)) {
            return $name;
        }
        $map['admin_id'] = $parent_agent_id;
        $name = M('agent')->where($map)->getField('admin_name');
        return $name;
    }

    public function getParentAgentInfo($parent_agent_id)
    {
        $where = [];
        $where['admin_id'] = $parent_agent_id;
        $where['status'] = 1;
        $parent_agent_info = M('agent')->where($where)->getField('admin_id,admin_name,dengji,shangji');

        $condition = [];
        $condition['is_agent'] = 1;
        $condition['agent_id'] = $parent_agent_id;
        $condition['operator_id'] = $this->operator_id;
        // 获取折扣
        $db_mid = M('mid_relation')->where($condition)->find();
        $rate = [];
        $rate['instance'] = $db_mid['instance'];
        $rate['system_disk'] = $db_mid['system_disk'];
        $rate['storage_disc'] = $db_mid['storage_disc'];
        $rate['network'] = $db_mid['network'];
        $parent_agent_info[$parent_agent_id]['rate'] = $rate;

        return $parent_agent_info[$parent_agent_id];
    }

    public function addAgentCommissionOrder($commission_order_info)
    {
        $agent_commission_order_record = M('agent_commission_order_record');
        $agent_commission_order_record->data($commission_order_info)->add();
    }
}